package com.jxd.ordersys.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jxd.ordersys.model.Meal;
import com.jxd.ordersys.service.IMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName MealContrller
 * @Description TODO
 * @Author 王云超
 * @Date 2024/9/20 10:23
 * @Version 1.0
 */
@RestController
public class MealController {
    // 设置图片保存路径为 D:\Workspace2024\ upload\images
    private final String uploadDir = "D:/Workspace2024/upload/images/";
    @Autowired
    IMealService mealService;

    @RequestMapping("getAllMeals")
    public List<Meal> getAllMeals() {
        return mealService.getAllMeals();
    }

    @RequestMapping("/addMeal")
    public String addMeal(@RequestParam("meal") String newMeal,
                          @RequestParam("image") MultipartFile file) throws IOException {
        try {
            // 使用 Jackson 反序列化 JSON 字符串为 Meal 对象
            ObjectMapper objectMapper = new ObjectMapper();
            Meal meal = objectMapper.readValue(newMeal, Meal.class);
            // 创建目录，如果不存在则创建
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 生成文件名并保存文件
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String imagePath = uploadDir + fileName;
            File dest = new File(imagePath);
            file.transferTo(dest); //将文件发送到该路径下

            // 保存餐品信息到数据库
            // 设置相对路径，便于前端通过 HTTP 访问
            meal.setImageurl("/images/" + fileName);

            // 保存餐品信息
            boolean addFlag = mealService.addMeal(meal);
            if (addFlag) {
                return "success";
            } else {
                return "error";
            }

        } catch (IOException e) {
            return "error";
        }
    }

    @RequestMapping("editMeal")
    public String updateMeal(@RequestParam("meal") String newMeal,
                             @RequestParam(value = "image", required = false) MultipartFile file) throws IOException {
        try {
            // 使用 Jackson 将 JSON 字符串反序列化为 Meal 对象
            ObjectMapper objectMapper = new ObjectMapper();
            Meal meal = objectMapper.readValue(newMeal, Meal.class);
            //如果传回文件,则说明修改了餐品的图片,将原本的图片删除掉,避免垃圾数据,若没有传回文件直接更新meal的信息
            if (file != null && !file.isEmpty()) {
                String oldImageUrl = meal.getImageurl();
                String oldImagePath = "D:/Workspace2024/upload" + oldImageUrl;

                // 删除旧图片文件
                File oldFile = new File(oldImagePath);
                if (oldFile.exists()) {
                    oldFile.delete();
                }

                // 保存新图片到 D:\Workspace2024\ upload\images
                String newFileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                String newImagePath = uploadDir + newFileName;
                File dest = new File(newImagePath);
                file.transferTo(dest);

                // 更新图片 URL
                meal.setImageurl("/images/" + newFileName);
            }
            boolean editFlag = mealService.editMeal(meal);
            if (editFlag) {
                return "success";
            } else {
                return "error";
            }
        } catch (IOException e) {
            return "error";
        }
    }

    @RequestMapping("/delMeal")
    public String delMeal(@RequestBody List<Integer> mealIds) {
        int delCount = 0;
        boolean delFlag = false;//删除的结果返回值

        // 遍历每个 mealId，删除数据库记录和对应图片
        for (Integer mealId : mealIds) {
            Meal meal = mealService.getMealById(mealId);
            // 获取图片文件路径
            String imageUrl = meal.getImageurl();
            String imagePath = "D:/Workspace2024/upload" + imageUrl;

            // 删除本地图片文件
            File imageFile = new File(imagePath);
            if (imageFile.exists()) {
                imageFile.delete();
            }
            // 删除数据库中的餐品记录
            delCount += mealService.delMealById(mealId);
        }
        if (delCount > 0) {
            delFlag = true;
        }
        if (delFlag) {
            return "success";
        } else {
            return "error";
        }
    }

}